const {
  UserChannel,
  Channel
} = require('../models/index') // 引入channel表
class ChannelService {
  async addUserChannel(userId, channel) {
    return UserChannel.create({
      userid: userId,
      channel
    })
  }

  async getUserChannel(userId) {
    let channel;
    const allChannel = await Channel.findAll()
    if (userId) {
      const count = await UserChannel.findAll({
        where: {
          userid: userId
        }
      })
      if (!count || count.length == 0) {
        channel = allChannel
      } else {
        const channelIds = JSON.parse(count[0].dataValues.channel)
        channel = channelIds.map(channelId => {
          const channel = allChannel.find(item => item.id === channelId)
          return channel
        })
      }
    } else {
      channel = allChannel
    }
    return channel
  }

  async getUserChannelByUserId(userId) {
    return UserChannel.findAll({
      where: {
        userid: userId
      }
    })
  }

  async updateUserChannel (userId, channel) {
    return UserChannel.update({
      channel: channel
    }, {
      where: {
        userid: userId
      },
    })
  }
}

module.exports = new ChannelService()